package com.itheima.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.Code;
import com.itheima.domain.Result;
import com.itheima.domain.User;
import com.itheima.exception.BusinessException;
import com.itheima.service.UserService;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     *http://localhost:8080/springmvc_03_ssm/user +get
     */
    @GetMapping("/findAll")
    public Result findAll(){
        List<User> list = userService.findAll();
        return list!=null&&list.size()>0 ? new Result(Code.QUERY_OK,"查询所有用户成功",list)
                :new Result(Code.QUERY_FAIL,"查询所有用户失败");

    }

    /**
     *http://localhost:8080/springmvc_03_ssm/user/1/3 +get
     * @param currentPage
     * @param pageSize
     */
    @GetMapping("/findByPage/{currentPage}/{pageSize}")
    public Result findByPage(@PathVariable Integer currentPage, @PathVariable Integer pageSize){
        if(currentPage<0 || pageSize<0){
            throw new BusinessException("当前页或者每页条数必须大于0");
        }
        PageInfo<User> pageInfo = userService.findByPage(currentPage, pageSize);
        return pageInfo.getList().size()>0?new Result(Code.QUERY_OK,"分页查询成功",pageInfo)
                :new Result(Code.QUERY_FAIL,"分页查询失败");
    }

    /**
     *http://localhost:8080/springmvc_03_ssm/user/1 +get
     * @param id
     */
    @GetMapping("/findById/{id}")
    public Result findById(@PathVariable Integer id){
        User user = userService.findById(id);
        return user!=null?new Result(Code.QUERY_OK,"根据id查询成功",user)
                :new Result(Code.QUERY_FAIL,"根据id查询失败");
    }

    /**
     *http://localhost:8080/springmvc_03_ssm/user +post
     * @param user
     */
    @PostMapping("/save")
    public Result save(@RequestBody @Validated User user, Errors errors){
        //获取异常信息
        if(errors.hasErrors()){
            List<FieldError> fieldErrors = errors.getFieldErrors();
            String multiMessage="";
            for (FieldError fieldError : fieldErrors) {
                //获取错误字段名称
                String field = fieldError.getField();
                //获取错误信息
                String defaultMessage = fieldError.getDefaultMessage();
                String message=field+"--"+defaultMessage;
                //创建异常对象并抛出，那么ProjectExceptionAdvice会获取到异常信息
                /*BusinessException exception = new BusinessException(message);
                throw exception;*/
                multiMessage+=(message+";");
            }
            throw new BusinessException(multiMessage);
        }

        int count = userService.save(user);
        return count>0?new Result(Code.SAVE_OK,"保存用户成功")
                :new Result(Code.SAVE_FAIL,"保存用户失败");
    }

    /**
     *http://localhost:8080/springmvc_03_ssm/user +put
     * @param user
     */
    @PutMapping("/update")
    public Result update(@RequestBody User user){
        int count = userService.update(user);
        return count>0?new Result(Code.UPDATE_OK,"修改用户成功")
                :new Result(Code.UPDATE_FAIL,"修改用户失败");
    }

    /**
     *http://localhost:8080/springmvc_03_ssm/user/8 +delete请求
     * @param id
     */
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id){
        int count = userService.delete(id);
        return count>0?new Result(Code.DELETE_OK,"删除用户成功")
                :new Result(Code.DELETE_FAIL,"删除用户失败");
    }

    /**
     *http://localhost:8080/springmvc_03_ssm/user/login +post
     * @param username
     * @param password
     * @param session
     */
    @PostMapping("/login")
    public Result login(String username, String password, HttpSession session){
        User loginUser = userService.login(username, password);
        if(loginUser!=null){
            session.setAttribute("user",loginUser);
        }
        return loginUser!=null?new Result(Code.LOGIN_OK,"登录成功"):new Result(Code.LOGIN_FAIL,"登录失败");
    }
}
